//
//  NovaSegmentBarChartView.swift
//  DaGlass
//
//  Created by 李然 on 2023/4/4.
//

import UIKit

struct NovaSegmentBarDateValue {
    
    let value: Double
    let color: UIColor
}

class NovaSegmentBarDataSet: NovaBaseChartData {
    
    var total: Double = 0
    var values: [NovaSegmentBarDateValue] = []
}

class NovaSegmentBarChartView: NovaBarChartView {
    
    override func makeUI() {
        super.makeUI()
        
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        drawBars(rect)
    }
    
    private func drawBars(_ rect: CGRect) {
        let xCount = self.data.count
        guard xCount > 0 else { return }

        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.saveGState()
        defer { context.restoreGState() }

        for (index, dataSet) in self.data.enumerated() {
            
            guard self.barRects.count > index else {
                return
            }
            let barRect = self.barRects[index]
            
            guard let dataSet = dataSet as? NovaSegmentBarDataSet else {
                return
            }
            var start = maxYAxisValue - dataSet.total
            start = max(start, 0)
            var y = (start - minYAxisValue)/(maxYAxisValue - minYAxisValue)  * chartFrame.height + chartFrame.minY
            for value in dataSet.values {
                context.setFillColor(value.color.cgColor)
                let height = chartFrame.height * value.value/(maxYAxisValue - minYAxisValue)
                let rect = CGRect(x: barRect.minX, y: y, width: barRect.width, height: height)
                let path = UIBezierPath(roundedRect: rect, cornerRadius: barCornerRadius)
                path.fill()
                y += height
            }
        }
    }

}
